package com.cdn.allmobilestore.ui;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cdn.allmobilestore.R;
import com.cdn.allmobilestore.model.AppInfo;
import com.cdn.allmobilestore.ulti.DownloadInstallManager;
import com.cdn.allmobilestore.ulti.GlobalApplication;
import com.cdn.allmobilestore.ulti.InstallChecker;
import com.cdn.allmobilestore.ulti.LocalAppManager;
import com.cdn.allmobilestore.ulti.Log;
import com.cdn.allmobilestore.ulti.Ulti;

public abstract class ActionArea extends LinearLayout {

	
	protected Context mContext;
	protected AppInfo mAppInfo;
	protected boolean iClicked = false;
	
	protected View.OnClickListener mArrangeClickListener = new View.OnClickListener()
	  {
	    public void onClick(View paramAnonymousView)
	    {
	    	if (!Ulti.isNetworkAvailable(mContext))
	        {    
	          Toast.makeText(mContext,mContext.getString(R.string.network_unavaliable),Toast.LENGTH_LONG).show();	          
	        }   
	        else
	        {  
	        	if(!iClicked)
	        	{	
	        		post(new Runnable()
	  		      	{
		  		        public void run()
		  		        {
		  		        	InstallChecker.checkAndInstall(ActionArea.this.mAppInfo, (Activity)ActionArea.this.getContext());
		  		        }
	  		      	});
	        		
	        		//
	        	}
	        	
	        }
	    }
	  };
	 private Handler mHandler = new Handler(); 
	 protected LaunchClickListener mLaunchClickListener = new LaunchClickListener();
	 private DownloadInstallManager.ProgressListener mProgressListener = new DownloadInstallManager.ProgressListener()
	  {

		@Override
		public void onProgressUpdate(String appId, final DownloadInstallManager.Progress progress) {
			ActionArea.this.mHandler.post(new Runnable()
	        {
	          public void run()
	          {
	        	  if (progress == null)
		  			return;           
	  	          switch (progress.status)
	  	          {              
	  	              case 0:            	 
	  	              case 2:
	  	                ActionArea.this.updateProgressPending(ActionArea.this.mAppInfo, progress);
	  	                break;
	  	              case 1:            	 
	  	                ActionArea.this.updateProgressConnecting(ActionArea.this.mAppInfo, progress);
	  	                break;
	  	              case 5:
	  	                ActionArea.this.updateProgressVerifying(ActionArea.this.mAppInfo, progress);
	  	                break;
	  	              case 6:
	  	                ActionArea.this.updateProgressInstalling(ActionArea.this.mAppInfo, progress);
	  	                break;
	  	              case 3:
	  	            	 ActionArea.this.iClicked = true;
	  	                ActionArea.this.updateProgressDownloading(ActionArea.this.mAppInfo, progress);
	  	                break;
	  	              case 4:
	  	                ActionArea.this.updateProgressPaused(ActionArea.this.mAppInfo, progress);
	  	                break;            	  
	  	              default:  
	  	                  break;  
	  	          }
	          }
	        });
		}	
     

		@Override
		public void onStateUpdate(String paramString, int paramInt1,
				int paramInt2) {
			 
			
		}
		  
	  };
	  

	public ActionArea(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		// TODO Auto-generated constructor stub
		this.mContext  = context;
		
	}

	/**Phong
	 * @param context
	 */
	public ActionArea(Context context) {
		super(context);
		this.setGravity(Gravity.BOTTOM);
		// TODO Auto-generated constructor stub
	}
	
	public void rebind(AppInfo appInfo)
	  {
	    rebind(appInfo, true);
	  }

	public void rebind(AppInfo appInfo, boolean isActionable)
	  {		
	    appInfo.updateAppStatus();	    
	    if (this.mAppInfo != null)
	    {
	    	DownloadInstallManager.getManager().removeProgressListener(this.mAppInfo.getId(), this.mProgressListener);
	    }
	    
	     //Log.v("ActionArea rebind:" + appInfo.status);	     
	     this.mAppInfo = appInfo;
	  
	     bindNormal(appInfo);
	    // DownloadInstallManager.getManager().addProgressListener(appInfo.getId(), this.mProgressListener);
	     if(!isActionable)
	     {
	       setVisibility(View.GONE);
	     }
	     else
	     {
    	    if (appInfo.status == AppInfo.AppStatus.STATUS_INSTALLED )
	        {
	          AppInfo localAppInfo = LocalAppManager.getManager().getLocalAppInfo(appInfo.getPackageName());
	          if( appInfo.getPackageName().equals(GlobalApplication._().getPackageName()) )
	          {
	        	  bindInstalled(appInfo);
    	          setVisibility(View.VISIBLE);
	          }
	          else if (localAppInfo == null)
	          {
	            Log.v("MarketActionArea status error for app " + appInfo.getPackageName() + " : local app does not exists, but status is STATUS_INSTAILLED");
	            
	          }
	          else if ( !localAppInfo.getVersion().replace(".", "").equals(appInfo.getVersion().replace(".", "")) )
	          {
	        	  try{	        		  
	        		  if(Float.parseFloat(appInfo.getVersion().replace(".", ""))  >= Float.parseFloat(localAppInfo.getVersion().replace(".", "")))
	        		  {
	        			bindUpdate(appInfo);
	      	             if (!isActionable)
	      	            	setVisibility(View.GONE);
	      		          //DownloadInstallManager.getManager().addProgressListener(appInfo.getId(), this.mProgressListener);
	        		  }
	        		  else
	        		  {
	        			bindInstalled(appInfo);
	      	            setVisibility(View.VISIBLE);
	        		  }
	        		  
	        	  }catch(Exception e){
	        		  Log.v(e.getMessage());
	        		  bindUpdate(appInfo);
      	              if (!isActionable)
      	            	setVisibility(View.GONE);
      		         // DownloadInstallManager.getManager().addProgressListener(appInfo.getId(), this.mProgressListener);
	        	  }
	            
	          }
	          else
	          {
	            bindInstalled(appInfo);
	            setVisibility(View.VISIBLE);
	          }
	        }
	        else if (appInfo.status == AppInfo.AppStatus.STATUS_INSTALLING )
	        {        	    
	          //AppInfo.get(appInfo.getId()).status = AppStatus.STATUS_INSTALLING;
	          bindInstalling(appInfo);
	          DownloadInstallManager.getManager().addProgressListener(appInfo.getId(), this.mProgressListener);
	          setVisibility(View.VISIBLE);		    	          
	          //DownloadInstallManager.getManager().removeTaskListener(mTaskListener);
	        } 
	       
	      }

	  }
	
	

	protected abstract void bindInstalled(AppInfo appInfo);

	protected abstract void bindInstalling(AppInfo appInfo);

	protected abstract void bindNormal(AppInfo appInfo);

	protected abstract void bindPrice(AppInfo appInfo);

	protected abstract void bindUpdate(AppInfo appInfo);

	protected abstract void updateProgressConnecting(AppInfo appInfo, com.cdn.allmobilestore.ulti.DownloadInstallManager.Progress progress);

	protected abstract void updateProgressDownloading(AppInfo appInfo, DownloadInstallManager.Progress progress);

	protected abstract void updateProgressInstalling(AppInfo appInfo, DownloadInstallManager.Progress progress);

	protected abstract void updateProgressPaused(AppInfo appInfo, DownloadInstallManager.Progress progress);

	protected abstract void updateProgressPending(AppInfo appInfo, DownloadInstallManager.Progress progress);

	protected abstract void updateProgressVerifying(AppInfo appInfo, DownloadInstallManager.Progress progress);
			
	protected abstract void updateProgressInstalled(AppInfo appInfo, DownloadInstallManager.Progress progress);
	
	protected class LaunchClickListener implements View.OnClickListener{
	    private Intent mIntent;	
	    protected LaunchClickListener()
	    {
	    }
	
	    private void showNotifyBubble()
	    {
	      Toast.makeText(ActionArea.this.mContext, ActionArea.this.mContext.getString(R.string.title_downloadx,ActionArea.this.mAppInfo.getName()), Toast.LENGTH_SHORT).show();
	    }
	
	    public void onClick(View view)
	    {
	      if (this.mIntent == null)
	        this.mIntent = ActionArea.this.getContext().getPackageManager().getLaunchIntentForPackage(ActionArea.this.mAppInfo.getPackageName());
	      if (this.mIntent == null)
	        showNotifyBubble();
	      else
	      {
	        try
	        {
	          ActionArea.this.getContext().startActivity(this.mIntent);
	        }
	        catch (ActivityNotFoundException localActivityNotFoundException)
	        {
	          showNotifyBubble();
	        }
	      }
	    }
	
	    public void setIntent(Intent paramIntent)
	    {
	      this.mIntent = paramIntent;
	    }
	  }
}
